<template>
  <div style="width: 100%; margin-top: 20px; margin-left: 20px" >
    <el-form :inline="true" :model="data" class="demo-form-inline">
      <el-form-item label="股票代码">
        <el-input
          v-model="data.code"
          style="width: 240px"
          placeholder="input stock code"
          @update:model-value="onInputChange"
      /></el-form-item>
      <el-form-item>
        <el-switch v-model="switch_beta_release" @change="on_switch_normal()" active-icon="" inline-prompt active-text="正式" inactive-text="模拟" style="--el-switch-on-color: #ff4949; --el-switch-off-color: #13ce66"/>
      </el-form-item>
      <el-form-item>
        <el-switch v-model="switch_normal_show" @change="on_switch_normal()" active-icon="" inline-prompt active-text="常规" inactive-text="常规"/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" plain @click="onClear()"  type="primary" >
              流程清除
        </el-button>

        <el-form-item label="选日期" style="margin-left: 20px" >
            <el-date-picker
                    v-model="data.dateTime"
                    type="date"
                    placeholder="Pick a day"
                    size="large"
                    @change="handleDateChange"
                />
          </el-form-item>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      ref="tableRef"
      row-key="code"
      :data="tableStock"
      style="width: 100%"
      v-if="tableStock.length > 0"
    >
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="TSCODE" label="代码" width="180" />
      <el-table-column prop="industryType" label="行业" width="180"/>
      <el-table-column prop="focus" label="操作" width="300" > 
        <template #default="scope">
          <el-button size="small" plain @click="onLoadConditionByCode(scope.row.TSCODE, scope.row.name)"  type="primary" >
              买入审核
            </el-button>
        </template>  
      </el-table-column>
    </el-table>

    <el-table
      ref="tableRef"
      row-key="code"
      :data="tableOrder"
      style="width: 100%"
      class="custom-border"
      v-if="tableOrder.length > 0"
      >
        <el-table-column prop="name" label="名称" width="150" />
        <el-table-column prop="code" label="代码" width="150" />
        <el-table-column prop="buyCount" label="持仓" width="100" >
          <template #default="scope">
            <el-text > {{scope.row.buyCount}}元 </el-text>
          </template>
        </el-table-column>
        <el-table-column prop="strA" label="策略" width="100" ></el-table-column>
        <el-table-column prop="strB" label="布局时机" width="160" ></el-table-column> 
        
        <el-table-column prop="sailId" label="审核码" width="120" >
          <template #default="scope">
            <el-text > {{scope.row.code.slice(0, 6) + scope.row.buyId}} </el-text>
          </template>
        </el-table-column> 
        <el-table-column prop="x" label="审核结果" width="250" >
          <template #default="scope">
            <div class="button-container">
                  <el-text v-show="getShenHeButtonStatus(scope.row.oneOk, 0)" style="margin-left:16px">审核中</el-text>
                  <el-button type="danger" :icon="CloseBold" circle size="small" v-show="getShenHeButtonStatus(scope.row.oneOk, 444)" style="margin-left:12px"/>               
                  <el-button type="success" :icon="Check" circle size="small" v-show="getShenHeButtonStatus(scope.row.oneOk, 666)"/>
            </div>
            {{onLoadConditionStatus(scope.$index, scope.row)}}
          </template>
        </el-table-column> 
        <el-table-column prop="focus" label="操作" width="120" > 
          <template #default="scope">
            <el-button size="small" plain @click="onLoadConditionNormal(scope.row)"  type="primary" >
              买入审核
            </el-button>
          </template>  
        </el-table-column>
        <el-table-column prop="note" label="说明" width="250" ></el-table-column> 
        <el-table-column prop="k" label="占位" width="500" ></el-table-column>
    </el-table>

    <div style="display: flex;width: 100%;margin-top: 20px;margin-bottom: 20px;" >  
        <el-text v-if="tableCondition.length > 0" style="color:#333333;font-size: 18px;font-weight: bolder" >{{data.validateStockName}}</el-text> 
        <el-text v-if="tableCondition.length > 0" style=" margin-left: 20px;margin-right:20px;color:#333333">{{data.validateStockCode}}</el-text>
        <el-button type="info" plain v-if="getStatusNotBtnIsShow(444)">
            审核不通过通过，无法操作
        </el-button>
        <el-button @click="onSubmit_AddOrder()" type="success"  v-if="getStatusBtnIsShow(666, 0)">
            买 入(审核通过)
        </el-button>
        <el-button @click="onClear()" type="Danger"  v-if="getStatusBtnIsShow(666, 1)">
            卖 出(审核通过)
        </el-button>
    </div>

    <el-table
      row-key="code"
      :data="tableCondition"
      style="width: 100%"
      class="custom-border"
      v-if="tableCondition.length > 0"
    >
    <el-table-column property="indicator" label="指标" width="150" />
          <el-table-column property="condition" label="审核条件" width="200" />
          
          <el-table-column prop="x" label="是否通过"  width="150">
              <template #default="scope">
                <div class="button-container">
                  <el-text v-show="shouldShowButton(scope.row, 0)" style="margin-left:16px">--</el-text>
                  <!-- <el-button type="warning" circle size="small" v-show="shouldShowButton(scope.row, 0)" style="margin-left:12px">待</el-button> -->
                  <el-button type="danger" :icon="CloseBold" circle size="small" v-show="shouldShowButton(scope.row, 2)" style="margin-left:12px"/>               
                  <el-button type="success" :icon="Check" circle size="small" v-show="shouldShowButton(scope.row, 1)"/>
                </div>
              </template>
          </el-table-column>
          <el-table-column property="mark" label="规则" width="250"></el-table-column>
          <el-table-column property="note" label="说明" width="1000">
            <template #default="scope">
                <el-text :style="{color:getNoteColor(scope.row.isOk)}">{{ scope.row.note }}</el-text>
            </template>
          </el-table-column>

    </el-table> 

    <!--订单-->
    <el-table
      v-loading="loading"
      row-key="code"
      :data="tableBookOrder"
      style="width: 100%"
      v-if="tableBookOrder.length > 0"
      class="custom-border"
    >
    <el-table-column prop="buyTime" label="买入时间" width="180" />
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="focus" label="盈亏" width="300" > 
        <template #default="scope">
          <el-text :style="{color:getIncreaseColor(scope.row.price, scope.row.buyPrice)}">{{ getIncreasePercent(scope.row.price, scope.row.buyPrice)}}</el-text>
        </template>  
      </el-table-column>
      <el-table-column property="note" label="说明" width="250"></el-table-column>
      <el-table-column property="mark" label="占位" width="2500"></el-table-column>
    </el-table>
  </div>
</template>
  
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { TableColumnCtx, TableInstance } from "element-plus";
import { reactive } from "vue";
import axios from "axios";
import { countdownEmits, ElMessage, ElMessageBox, ElLoading} from "element-plus";
import ClipboardJS from 'clipboard';
import { useStore } from 'vuex';
import type { Action } from 'element-plus'
import {Check,Delete,Edit,Message,Search, Star, CloseBold,Close,QuestionFilled
} from '@element-plus/icons-vue';
import { fa } from "element-plus/es/locale";

const data = reactive({
  code: "",
  dateTime: "",
  validateStockName: '',
  validateStockCode:  ''
});
const switch_normal_show = ref(false)
const switch_beta_release = ref(false)

const loading = ref(false);
const tableRef = ref<TableInstance>();

const tableStock = ref([]);
const tableOrder = ref([]);
const tableCondition = ref([]);
const tableBookOrder = ref([]);

const store = useStore();
const validateStatus = ref(0);
const orderStatus = ref(0);

const onInputChange = (newValue, oldValue) => {
    console.log("Input changed:", newValue);
    const containsChinese = /[\u4e00-\u9fa5]/.test(newValue);
    if (newValue === '') {
      tableStock.value = []
    } else {
      if (containsChinese) {
        onSearh(newValue, 2);
      } else if (newValue.length == 6) {
        onSearh(newValue, 1);
      }
    }
  };

  const onSearh = (str: string, type: number) => {
    console.log("submit!");
    const encodedName = encodeURIComponent(str);
    const api = "api/plat/stockNowPrice/getStockListByName?name=" + encodedName;
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        tableStock.value = response.data.data;
        console.log(tableStock);
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  };


const onSearhAll = () => {
  console.log("submit!");
  const api = "api/plat/stockOrder/findAll?recordDate=" + data.dateTime;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableOrder.value = response.data.data;
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onLoadBookOrder = () => {
  onClear()
  const api = "api/plat/bookOrderRecord/findAll";
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableBookOrder.value = response.data.data;
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
}

const getIncreaseColor = (price:number, buyPrice:number) => {
      return price - buyPrice > 0 ? "#F56C6C" : "#67C23A";
}

const getIncreasePercent = (price:number, buyPrice:number) => {
      return ((price - buyPrice) * 100 / buyPrice).toFixed(2) + "%";
}

const onSubmit_AddOrder = () => {
  onClear()
  const api = "api/plat/bookOrderRecord/addOrder?tsCode=" + data.validateStockCode + "&dayTime=" + data.dateTime;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
        if (response.data.status == 200) {
          ElMessage({
            message: "下单成功",
            type: "success",
          });
          onLoadBookOrder()
        } else {
          ElMessage({
            message: response.data.message,
            type: "warning",
          });
        }
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
}

const onSubmit_UpdateOrder = (pid: number,pstatus:number) => {
  axios.put("api/plat/stockOrder/update", {
    id:pid,
    status:pstatus,
  }).then((response) => {
    console.log(response);
    if (response.data.status == 200) {
        ElMessage({
          message: "签字完成",
          type: "success",
        });
      } else {
        ElMessage({
          message: "签字失败",
          type: "success",
        });
      }
  })
}

interface StockOrder {
  id: number;
  name: string;
  code: string;
  focus: number;
  status: number;
  oneOk: number;
  buyId: number;//买入策略
  sailId: number;//卖出策略
}

interface StockIndicatorOk {
    id: number;
    recordId: number;
    indicator: string;
    condition: string;
    isOk: number;
    data: number;
    type: string;
    note: string;
    mark: string;
  }

  const onLoadConditionNormal = (row: StockOrder) => {
    console.log("submit!");
    data.validateStockCode = row.code;
    data.validateStockName = row.name;
    const loadingInstance = ElLoading.service({ fullscreen: true, lock: true, text: row.name + '审核结果计算中...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.8)' })
    const api = "api/plat/stockIndicatorOk/findConditionListByNormal?tsCode=" + row.code + "&sailBuyCode=" + (row.status == 0 ? row.buyId : row.sailId);
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        tableStock.value = [];
        tableCondition.value = response.data.data;
        loadingInstance.close();
        validateStatus.value = response.data.isOk;
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  };

  const  onLoadConditionStatus = (index:number,row: StockOrder) => {
    console.log("submit!");
    data.validateStockCode = row.code;
    data.validateStockName = row.name;
    const api = "api/plat/stockIndicatorOk/findConditionListByNormal?tsCode=" + row.code + "&sailBuyCode=" + (row.status == 0 ? row.buyId : row.sailId);
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        tableOrder.value[index].oneOk = response.data.isOk;
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      }); 
  };

  const onLoadConditionByCode = (tsCode, name) => {
    console.log("submit!");
    data.code = ""
    data.validateStockCode = tsCode;
    data.validateStockName = name;
    const loadingInstance = ElLoading.service({ fullscreen: true, lock: true, text: name + '审核结果计算中...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.8)' })
    const api = "api/plat/stockIndicatorOk/findConditionListByCode?tsCode=" + tsCode + "&sailBuyCode=100";
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        tableStock.value = [];
        tableCondition.value = response.data.data;
        loadingInstance.close();
        validateStatus.value = response.data.isOk;
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  };


  const onClear = () => {
    tableCondition.value = [];
    validateStatus.value = 0;
  };

  const on_switch_normal = () => {
    if(switch_normal_show.value) {
      onSearhAll()
    } else {
      tableOrder.value = []
    }
  };

  const shouldShowButton = (row: StockIndicatorOk, value) => {
      if (row.isOk == value) {
        return true;
      }
    }  

    const getIsShow = (value:number) => {
      if (validateStatus.value == value) {
        return true;
      } else {
        return false;
      }
    }   

    const getShenHeButtonStatus = (oneOk:number, value:number) => {
      if (oneOk == value) {
        return true;
      } else {
        return false;
      }
    } 
    
    const getStatusBtnIsShow = (validate:number, order:number) => {
      if (validateStatus.value == validate && orderStatus.value == order) {
        return true;
      } else {
        return false;
      }
    }   

    const getStatusNotBtnIsShow = (validate:number) => {
      if (validateStatus.value == validate) {
        return true;
      } else {
        return false;
      }
    } 

    const getNoteColor = (strA:number) => {
      if (strA == 2) {
        return '#F56C6C'; 
      } else {
        if (strA == 0) {
          return '#67C23A'; 
        } 
      }
    }

const handleDateChange = (val) => {
        console.log('选择了新的日期/时间:', val);
        const date = new Date(val)
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要加1
        const day = ('0' + date.getDate()).slice(-2);
        const dayTime = `${year}-${month}-${day}`;
        console.log('选择了新的日期/时间:', dayTime);

        const date1 = new Date(getToday());
        const date2 = new Date(dayTime);

        if (date1 < date2) {
          ElMessage({
            message: "日期不能晚于今天",
            type: "error",
          });
          return;
        }

        data.dateTime = dayTime;
    };

onMounted(() => {
      data.dateTime = getToday();
      onLoadBookOrder()
      const clipboard = new ClipboardJS('.btn-copy', {
        text: () => data.validateStockCode
      });

      clipboard.on('success', (e) => {
        console.log('Text copied to clipboard');
        e.clearSelection();
      });

      clipboard.on('error', (e) => {
        console.error('Failed to copy text: ', e);
      });
    });

    const handleBuySure = (index: number, row: StockOrder) => {
          ElMessageBox.alert('请遵守交易记录，切勿随心操作，挣钱不易', '签字确认', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: '确定',
        center:true,
        callback: (action: Action) => {
          onSubmit_UpdateOrder(row.id, 10)
        },
      })
    };

    const getToday = () =>  {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
      const day = String(today.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    }
</script>

<style >
.custom-border {
  border: 0.5px solid #dfe6ec;
}

.custom-border th, .custom-border td {
  border: 0.5px solid #dfe6ec;
}


</style >